import React from 'react'
import produce from 'immer'

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
function generateFormFields(fieldsId = [], obj = {}, state = {}) {
  const res = {};
  fieldsId.forEach((id) => {
    if (state.formFields) {
      let field = state.formFields[id]
      if (id in obj && obj[id] !== field.value) {
        res[id] = {
          value: obj[id]
        }
      } else {
        res[id] = field
      }
    } else {
      res[id] = { value: null }
    }
  })
  return res
}
function shallowCompareFieldsValue(fieldsId = [], props, state) {
  return !fieldsId.every(id => !(id in props) || props[id] === state.formFields[id].value)
}
export function wrapForm(fieldsId = []) {
  return function (WrappedComponent) {
    class SxFormWrapper extends React.PureComponent {
      static getDerivedStateFromProps(props, state) {
        if (
          shallowCompareFieldsValue(fieldsId, props, state)
        ) {
          return {
            formFields: generateFormFields(fieldsId, props, state)
          }
        }
        return null
      }
      state = {
        formFields: generateFormFields(fieldsId)
      }
      updateFormFields = (newFields) => {
        this.setState(produce((draft) => {
          Object.assign(draft.formFields, newFields)
        }))
      }
      render() {
        return (
          <WrappedComponent {...this.props} formFields={this.state.formFields} updateFormFields={this.updateFormFields} />
        )
      }
    }
    SxFormWrapper.displayName = `SxFormWrapper(${getDisplayName(WrappedComponent)})`;
    return SxFormWrapper
  }
}
